<template>
  <div class="app-container home">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="agent名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入agent名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="agent类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="agent类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in agent_type_options"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in status_type_options"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        :mode="true"
        :isTable.sync="isTable"
        @queryTable="getAgentList"
      >
      </right-toolbar>
    </el-row>
    <el-empty v-if="baseList.length === 0" description="暂无数据"></el-empty>
    <div v-else>
      <el-table v-if="isTable" v-loading="loading" :data="baseList">
        <el-table-column label="agent名称" align="center" prop="name" />
        <el-table-column prop="type" label="agent类型">
          <template slot-scope="scope">
            {{ getLabelfromValue(agent_type_options, scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <span :style="{ color: corlorList[scope.row.status] }">
              {{
                getLabelfromValue(
                  status_type_options,
                  scope.row.status
                )
              }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-link icon="el-icon-edit" @click="handleUpdate(scope.row)"
                >编辑</el-link
              >
          </template>
        </el-table-column>
      </el-table>
      <el-row
        v-else
        v-loading="loading"
        class="knowledgeBaseContent"
        :gutter="10"
      >
        <el-col
          v-for="item in baseList"
          :key="item.key"
          :xs="12"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="6"
          class="knowledgeBaseItem"
        >
          <div class="agent-content">
            <el-descriptions
              :title="item.name"
              :column="1"
              class="grid-el-descriptions"
            >
              <template #title>
                <svg-icon icon-class="aiAgent" />
                <span :title="item.name">{{ item.name }}</span>
              </template>
              <el-descriptions-item label="类型">
                {{ getLabelfromValue(agent_type_options, item.type) }}
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <span
                  :class="[item.status == '1' ? 'openState' : 'closeState']"
                >
                  {{ getLabelfromValue(status_type_options, item.status) }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="描述">
                <span class="descriptions" :title="item.description">
                  {{ item.description }}
                </span>
              </el-descriptions-item>
            </el-descriptions>
            <div class="knowledgeBaseItem-bottom">
              <el-link icon="el-icon-edit" @click="handleUpdate(item)"
                >编辑</el-link
              >
            </div>
          </div>
        </el-col>
      
      </el-row>
    </div>
    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getAgentList"
      />
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form v-if="clientType.indexOf('dianjin')>-1" ref="dianjinForm" :model="dianjinForm" :rules="dianjinRules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="dianjinForm.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="权限配置" prop="roleIdList">
          <el-select
            multiple
            v-model="dianjinForm.roleIdList"
            placeholder="请选择角色"
            clearable
            style="width: 240px"
          >
            <!-- @change="handleChangeSelect" -->
            <el-option
              v-for="dict in roleId_type_options"
              :key="dict.roleId"
              :label="dict.roleName"
              :value="dict.roleId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="功能介绍" prop="description">
          <el-input
            type="textarea"
            placeholder="请输入功能介绍"
            v-model="dianjinForm.description"
            show-word-limit
          >
          </el-input>
        </el-form-item>
      </el-form>
      <el-form v-else ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择类型"
            clearable
            style="width: 240px"
            @change="changeType"
            @clear="clearType"
          >
            <el-option
              v-for="dict in agent_type_options"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="应用分类"
          prop="category"
          v-if="form.type == 'KNOWLEDGE_RETRIEVAL'"
        >
          <el-select
            v-model="form.category"
            placeholder="请选择应用分类"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in category_type_options"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开启多轮" prop="enableMultiTurn">
          <el-radio-group v-model="enableMultiTurn">
            <el-radio
            v-for="dict in enableMultiTurn_type_options"
            :key="dict.value"
            :label="dict.value"
            >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
       
        <el-form-item label="选择LLM模型" prop="modelId">
          <!-- @change="handleChange" -->
          <el-cascader
            v-model="form.modelId"
            :options="modelId_type_options"
            placeholder="请选择LLM模型"
            style="width: 240px"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="搜索引擎"
          prop="webSearcher"
          v-if="form.type == 'KNOWLEDGE_RETRIEVAL'"
        >
          <el-select
            v-model="form.webSearcher"
            placeholder="请选择搜索引擎"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in webSearcher_type_options"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限配置" prop="roleIdList">
          <el-select
            multiple
            v-model="roleIdList"
            placeholder="请选择角色"
            clearable
            style="width: 240px"
          >
            <!-- @change="handleChangeSelect" -->
            <el-option
              v-for="dict in roleId_type_options"
              :key="dict.roleId"
              :label="dict.roleName"
              :value="dict.roleId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="示例问题" prop="examples">
          <template v-if="examples && examples.length > 0">
            <div
              :key="index"
              v-for="(example, index) in examples"
              style="display: flex; align-items: center"
            >
              <el-input v-model="example.content" placeholder="示例问题" />
              <i class="el-icon-delete" @click="deleteExample(index)"></i>
            </div>
          </template>
          <el-button plain @click="addExample">+ 新增示例问题</el-button>
        </el-form-item>
        <el-form-item label="知识库" prop="knowledgeBases">
          <el-select v-model="knowledgeBases" multiple placeholder="关联知识库">
            <el-option
              v-for="item in knowledgeBases_type_options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            type="textarea"
            placeholder="请输入助理描述"
            v-model="form.description"
            show-word-limit
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="clientType.indexOf('dianjin')>-1" type="primary" @click="submitDainjinForm">确 定</el-button>
        <el-button v-else type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBase,
  addBase,
  updateBase,
  knowledgeListBase,  // 知识库列表
} from "@/api/ai/agent";
import { addDianjinBase } from "@/api/ai/dianjin";
// 角色列表
import { listRole } from "@/api/system/role";
// 模型列表
import { listBase as modelListBase } from "@/api/ai/model";

import { getLabel, getNameFromValue } from "@/utils/index";

export default {
  name: "Agent",
  data() {
    return {
      corlorList: ["#FA5151", "#1890FF"],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      isTable: true,
       // 总条数
       total: 0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 知识库表格数据
      baseList: [],
      // 弹出层标题
      title: "新增Agent",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      dianjinForm: {},
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        type: undefined,
        status: undefined,
      },
      // 表单校验
      rules: {
        // tenantId: [{ required: true, message: "不能为空", trigger: "blur" }],
        modelId: [
          { required: true, message: "LLM模型不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
        webSearcher: [
          { required: true, message: "搜索引擎不能为空", trigger: "blur" },
        ],
        description: [
          { required: true, message: "描述不能为空", trigger: "blur" },
        ],
      },
      // 表单校验
      dianjinRules: {
       
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        description: [
          { required: true, message: "描述不能为空", trigger: "blur" },
        ],
      },
      // 类型
      agent_type_options: [{ label: "知识问答", value: "KNOWLEDGE_RETRIEVAL" }],
      // 是否多轮
      enableMultiTurn_type_options: [
        { label: "开启", value: true },
        { label: "关闭", value: false },
      ],
      // 应用分类
      category_type_options: [{ label: "知识问答", value: "KNOWLEDGE_REAL" }],
      // 搜索引擎
      webSearcher_type_options: [
        { label: "不使用搜索引擎", value: "not_using" },
        { label: "百度", value: "baidu" },
      ],
      // 示例问题
      examples: [],
      // 请选择LLM模型
      modelId_type_options: [],
      clientType: 'rag',
      // 角色列表
      roleId_type_options: [],
      roleIdList: [],
      // 知识库
      knowledgeBases_type_options: [],
      // 选中的知识库
      knowledgeBases: [],
      status_type_options: [
        { label: "正常", value: "1" },
        { label: "禁用", value: "0" },
      ],
      enableMultiTurn: false,
    };
  },
  created() {
    this.getAgentList();
    this.getModelList();
    this.getRoleList();
    this.getknowledgeBasesList();
  },
  methods: {
    // 字典显示的方法
    getLabelfromValue(dict, value) {
      return getLabel(dict, value);
    },
    /** 查询Agent列表 */
    getAgentList() {
      this.loading = true;
      listBase(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.baseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getAgentList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询角色列表 */
    getRoleList() {
      listRole({}).then((response) => {
        this.roleId_type_options = response.rows || [];
        localStorage.setItem('roleList', JSON.stringify(this.roleId_type_options));
      });
    },
    /** 查询Model列表 */
    getModelList() {
      modelListBase({}).then((response) => {
      if(response.code==200){
        if(response.clientType.indexOf('dianjin')>-1){
          this.clientType = 'dianjin';
          this.modelId_type_options = response.data || [];
          // console.log('this.modelId_type_options',this.clientType,this.modelId_type_options)
        }else{
          this.clientType = 'rag';
          const arr = [];
          const roleList = response.data || [];
          roleList.forEach((el) => {
            let obj = {};
            obj["label"] = el.name;
            obj["value"] = el.id;
            if (el.subCandidateValues && el.subCandidateValues.length > 0) {
              obj["children"] = [];
              el.subCandidateValues.forEach((subEl) => {
                let subObj = {};
                subObj["label"] = subEl.name;
                subObj["value"] = subEl.id;
                obj["children"].push(subObj);
              });
            }
            arr.push(obj);
          });
          this.modelId_type_options = arr;
        }
        localStorage.setItem('modelList', JSON.stringify(this.modelId_type_options));
      }
      });
    },
    /** 查询知识库列表 */
    getknowledgeBasesList() {
      knowledgeListBase({}).then((response) => {
        this.knowledgeBases_type_options = response.rows || [];
        localStorage.setItem('knowledgeBasesList', JSON.stringify(this.knowledgeBases_type_options));
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.dianjinReset();
    },
    // 表单重置
    reset() {
      (this.form = {
        name: null,
        type: null,
        modelId: null,
        description: null,
        category: null,
        webSearcher: null,
        enableSearch: 0,
        enableLlmEnhanceQuery: 0,
        enableLlmTextImprove: 0,
        enableLlmTextToImage: 0,
        status: 1,
      }),
        // getNameFromValue(this.modelId_type_options, this.form.modelId);
        (this.examples = []);
      this.knowledgeBases = [];
      this.roleIdList = [];
      this.enableMultiTurn = false;
      this.resetForm("form");
    },
    // 表单重置
    dianjinReset() {
      (this.form = {
        name: null,
        description: null,
        botMode: 0,
        roleIdList: [],
      }),
      this.resetForm("dianjinForm");
    },
    /** 提交按钮 */
    submitDainjinForm() {
      this.$refs["dianjinForm"].validate((valid) => {
        if (valid) {
          addDianjinBase(this.dianjinForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getAgentList();
            });
          }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const form = this.getFormInfo();
          if (this.form.id != null) {
            updateBase(form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getAgentList();
            });
          } else {
            addBase(form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getAgentList();
            });
          }
        }
      });
    },

    /** 新增按钮操作 */
    handleAdd() {
      if (this.clientType.indexOf('dianjin')>-1) {
        this.dianjinReset();
      }else {
        this.reset();
      }
      this.open = true;
      this.title = "新增Agent";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (this.clientType.indexOf('dianjin')>-1) {
        this.$router.push("/agent/edit-agent/" + row.id);
      }else {
        this.reset();
        const id = row.id || this.ids;
        row.openRagSync = row.openRagSync + "";
        this.form = JSON.parse(JSON.stringify(row));
        this.getFormValue(row);
        this.open = true;
        this.title = "修改Agent";
      }
      // console.log('row',row);
      // 编辑多个agent时，agentData存储的值有问题，暂用方法，可以做成调接口的方式
      // localStorage.setItem('agentData', JSON.stringify(row));
      // this.$router.push({name: 'agentEdit',param});
    },
    // 更改类型
    changeType(event) {
      if (event == "KNOWLEDGE_RETRIEVAL") {
        this.form.category = "KNOWLEDGE_REAL";
      }
    },
    // 清空类型
    clearType(event) {
      if (!event) {
        this.form.category = null;
      }
    },
    // 添加示例
    addExample() {
      this.examples.push({ content: "" });
    },
    // 删除示例
    deleteExample(index) {
      this.examples.splice(index, 1);
    },
    // 新增/修改表单
    getFormInfo() {
      const agentConfig = {
        category: this.form.category,
        webSearcher: this.form.webSearcher,
      };
      const knowledgeBases = this.getKnowledgeBases();
      if (knowledgeBases.length > 0) {
        agentConfig["knowledge"] = knowledgeBases;
      }
      const form = Object.assign(this.form, {
        multiTurnConfig: {
          enableMultiTurn: this.enableMultiTurn,
        },
        examples: this.examples.map((item) => {
          return item.content;
        }),
        modelConfig: [
          {
            modelType: "LLM",
            modelId: this.form.modelId,
          },
        ],
        agentConfig: JSON.stringify(agentConfig),
        roleIdList: this.roleIdList,
      });
      return form;
    },
    // 获取修改值
    getFormValue(row) {
      // 获取示例问题
      let examples = [];
      if (row.examples) {
        row.examples.forEach((el) => {
          examples.push({ content: el });
        });
      }
      this.examples = examples;
      if (row.modelConfig && row.modelConfig[0] && row.modelConfig[0].modelId) {
        // 获取模型
        this.form.modelId = row.modelConfig[0].modelId;
        // this.form.name = getNameFromValue(this.modelId_type_options, this.form.modelId);
      }
      if (row.agentConfig) {
        let agentConfig = JSON.parse(row.agentConfig);
        // 获取应用种类
        if (agentConfig.category) {
          this.form.category = agentConfig.category;
        }
        // 获取搜索引擎
        if (agentConfig.webSearcher) {
          this.form.webSearcher = agentConfig.webSearcher;
        }
        // 获取关联知识库
        if (agentConfig.knowledge && agentConfig.knowledge.length > 0) {
          const knowledgeBases = [];
          agentConfig.knowledge.forEach((el) => {
            knowledgeBases.push(el.id);
          });
          this.knowledgeBases = knowledgeBases;
        }
      }
      // 获取是否多轮
      let enableMultiTurn = false;
      if (row.multiTurnConfig && "enableMultiTurn" in row.multiTurnConfig) {
        enableMultiTurn = row.multiTurnConfig.enableMultiTurn;
      }
      this.enableMultiTurn = enableMultiTurn;
      this.roleIdList = row.roleIdList;
    },
    // 获取关联知识库信息
    getKnowledgeBases() {
      let arr = [];
      if (this.knowledgeBases && this.knowledgeBases.length > 0) {
        this.knowledgeBases.forEach((el) => {
          const filterItem = this.knowledgeBases_type_options.filter((item) => {
            return item.id == el;
          });
          if (filterItem && filterItem[0]) {
            let obj = {};
            obj["id"] = filterItem[0].id;
            obj["kb_id"] = filterItem[0].ragCategoryId;
            obj["kb_name"] = filterItem[0].name;
            obj["key"] = filterItem[0].ragCategoryId;
            obj["label"] = filterItem[0].name;
            obj["value"] = filterItem[0].ragCategoryId;
            arr.push(obj);
          }
        });
      }
      return arr;
    },
  },
};
</script>

<style scoped lang="scss">
.el-row.knowledgeBaseContent {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }

  .knowledgeBaseItem {
    border-radius: 4px;
    margin-bottom: 10px;

    .agent-content {
      border-radius: 12px;
      min-height: 36px; // background: #f6f7ff;
      border: 1px solid #e5e5e5;
      box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.1);
      padding: 10px;
      padding-bottom: 0;
    }
  }
}

.knowledgeBaseItem-bottom {
  padding: 8px;
  text-align: right;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  .el-link.el-link--default {
    margin-left: 4px;
  }
}
.el-radio input[aria-hidden="true"] {
  display: none !important;
}

.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
  box-shadow: none !important;
}
</style>

<style lang="scss">
.agent-content {
  font-size: 16px;
  color: #0e0e0e;
  line-height: 22px;
  .el-descriptions__header {
    padding-bottom: 10px;
    margin-bottom: 6px;
    border-bottom: 1px solid #f1f1f1;
    padding-left: 10px;
  }
  .el-descriptions__body {
    border-bottom: 1px solid #f1f1f1;
    padding-bottom: 10px;
    height: 100px;
    .el-descriptions-row {
      .el-descriptions-item__cell {
        padding-bottom: 4px;
      }
    }
  }
  .el-descriptions__title {
    font-size: 16px;
    color: #0e0e0e;
    line-height: 22px;
    font-weight: 400;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
    white-space: nowrap;
    .svg-icon {
      margin-right: 4px;
    }
  }
  .closeState {
    color: #f56c6c;
  }

  .openState {
    color: #67c23a;
  }

  .descriptions {
    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
}
</style>
